<?php


namespace App\Http\Controllers\Backend;


use App\Constant\CompanyConstant;
use App\Http\Requests\Backend\Administrator\EditPasswordRequest;
use App\Http\Requests\Company\Administrator\AdministratorRequest;
use App\Models\AdministratorRelation;
use App\Models\AdministratorRole;
use App\Services\Member\Interfaces\UserServiceInterface;
use App\Services\Member\Models\User;
use App\Services\Member\Services\UserService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class AdministratorController extends BaseController
{

    /**
     * 管理员列表
     * @return JsonResponse
     */
    public function index(Request $request)
    {

        $keywords = $request->input('keywords', '');
        $administrators = AdministratorRelation::query()
            ->with(['members:id,nick_name,avatar'])
            ->when($keywords, function ($query) use ($keywords) {
                $userIds = User::query()
                    ->where('nick_name', 'like', '%' . $keywords . '%')
                    ->orWhere('mobile', $keywords)->select(['id'])->get()->pluck('id');
                $query->whereIn('user_id', $userIds);

            })
            ->orderByDesc('id')
            ->paginate(request()->input('size', 10));

        return $this->successData($administrators);
    }

    public function add()
    {
        $roles = AdministratorRole::query()->select(['id', 'display_name'])->get();
        return $this->successData([
            'roles' => $roles,
        ]);
    }

    /**
     * 新增管理员账户
     * @param AdministratorRequest $request
     * @return JsonResponse
     */
    public function store(AdministratorRequest $request)
    {
        $companyId = $this->loginCompanyId();
        $data = $request->filldata();
        $administrator = User::query()->where('id',$data['user_id'])->firstOrFail();
        DB::transaction(function () use ($data,$administrator,$companyId) {

            //新增成员跟店铺的关系
            $administrator->companies()->attach($companyId);

            //成员的角色关系
            $administrator->roles()->sync($data['role_ids']);

            /**
             * @var UserService  $userService
             **/
            $userService=  app()->make(UserServiceInterface::class);

            $userService->updateCompanyAdministrator($data['user_id']);

        });


        return $this->success();
    }

    /**
     * 编辑管理员账户
     * @param $id
     * @return JsonResponse
     */
    public function edit($id)
    {
        $administrator = User::query()->with(['roles'])->where('id', $id)->firstOrFail();
        return $this->successData($administrator);
    }


    /**
     * 更新管理员账户
     * @param $id
     * @return JsonResponse
     */
    public function update(AdministratorRequest $request, $id)
    {
        $administrator = User::query()->where('id', $id)->firstOrFail();

        $administrator->roles()->sync($request->input('role_ids', []));

        return $this->success(__('更新成功'));
    }

    /**
     * 修改密码
     * @param EditPasswordRequest $request
     * @return JsonResponse
     */
    public function editPasswordHandle(EditPasswordRequest $request)
    {
        $administrator = Auth::guard(CompanyConstant::GUARD)->user();

        if (!Hash::check($request->input('old_password'), $administrator['password'])) {
            return $this->error(__('原密码错误'));
        }

        $administrator->fill($request->filldata())->save();

        return $this->success();
    }


    /**
     * 删除管理员
     * @param $id
     * @return JsonResponse
     */
    public function delete($id): JsonResponse
    {
        $companyId = $this->loginCompanyId();
        $administrator = User::query()->where('id', $id)->firstOrFail();
        if ($administrator->couldDestroy()) {
            return $this->error(__('当前用户是超级管理员账户无法删除'));
        }
        DB::transaction(function () use ($companyId, $administrator) {

            //解除公司印射关系
            $administrator->companies()->detach($companyId);

            //解除店铺角色关系
            $administrator->roles()->delete();

            /**
             * @var UserService  $userService
             **/
            $userService=  app()->make(UserServiceInterface::class);
            //更新user表的印射关系
            $userService->updateCompanyAdministrator($administrator['id']);

        });


        return $this->success(__('删除管理员成功'));
    }
}
